﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.Specialized;
using Core;
using System.Xml.Serialization;
using System.IO;

namespace Web
{
    public class ReqWrapperQuery
    {
        protected T LoadFromXml<T>(string xml, dynamic data = null) {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(SqlSetting));
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(xml);
            MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length);
            var sqllSetting = xmlSerializer.Deserialize(ms);
            return (T)sqllSetting;
        }
        private NameValueCollection data;

        //-- GET data model: sortName=[]&sortOrer=[]&pageSize=[]&pageNumber=[]
        public ReqWrapperQuery(NameValueCollection nvc) {
            data = nvc;
        }

        public ParamQuery ToParam(string xml) {
            xml = GetXml(xml);
            var setting = LoadFromXml<SqlSetting>(xml);
            PopulateSetting(setting);
            var paramQuery = new ParamQuery();
            paramQuery.Select = setting.Select;
            paramQuery.From = setting.From;
            paramQuery.Where = setting.Where.GetSql();
            paramQuery.SortName = setting.SortName;
            paramQuery.SortOrder = setting.SortOrder;
            paramQuery.PageNumber = setting.PageNumber;
            paramQuery.PageSize = setting.PageSize;
            return paramQuery;

        }


        protected virtual string GetXml(string xml) {
            if (xml.EndsWith(".xml", StringComparison.InvariantCultureIgnoreCase)) {
                var path = HttpContext.Current.Server.MapPath("~\\SqlSettings\\" + xml);
                using (StreamReader sr = new StreamReader(path)) {
                    return sr.ReadToEnd();
                }
            } else {
                return xml;
            }
        }


        private void PopulateSetting(SqlSetting setting) {
            if (data == null) return;
            setting.SortName = data["sortName"] + "";
            setting.SortOrder = data["sortOrder"] + "";
            setting.PageSize = Convert.ToInt32(data["pageSize"]);
            setting.PageNumber = Convert.ToInt32(data["pageNumber"]);
            var nvc = data as NameValueCollection;
            setting.Where.Fields.ForEach(x => {
                if (nvc.AllKeys.Contains(x.Name)) {
                    x.Value = nvc[x.Name];
                }
            });
        }
    }
}